#include <stdlib.h>

#include "__ThreadManForUser.h"
#include "../host/host.h"

#include "__sceAudio.h"

void __AudioInit()
{
#ifndef NO_AUDIO
    host_initAudio(MAX_CHANNEL);
#endif
}

void __AudioUpdate()
{
#ifndef NO_AUDIO
    host_audioUpdate();
    if (__KernelResumeThreads(WAITTYPE_AUDIOCHANNEL, 0, RESUMETYPE_NONE))
        __KernelReSchedule();
#endif
}

void __AudioShutdown()
{
#ifndef NO_AUDIO
    host_freeAudio();
#endif
}

void __AudioPlay(AudioChannel *chan __attribute__((unused)), u8 channelId __attribute__((unused)))
{
#ifndef NO_AUDIO
    u8 stereo = (chan->format == AUDIO_FORMAT_STEREO);
    u32 i;
    void *buf;

    if (!mem_isOk(chan->sampleAddr)) {
        _log(ERR, AUDIO, "Invalid sample address!");
        return;
    }

    buf = malloc(sizeof(u16) * (stereo ? 2 : 1) * chan->sampleCount);

    for (i = 0; i < chan->sampleCount; i++)
    {
        if (stereo)
            ((u32*)buf)[i] = mem_read32(chan->sampleAddr + i * 4);
        else
            ((u16*)buf)[i] = mem_read16(chan->sampleAddr + i * 2);
    }

    if (host_queueBuffer(buf, chan->sampleCount, stereo, channelId))
#endif
        __KernelWaitCurThread(WAITTYPE_AUDIOCHANNEL, channelId, 0, 0, 0);
#ifndef NO_AUDIO

    free(buf);
#endif
}

